//
//  AppDelegate.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/2.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import <AdSupport/AdSupport.h>
#import "FLRestorePurchaseViewController.h"
#import "FLPagingScrollViewController.h"
#import "FLVideoDrawViewController.h"
#import "FLRecordedViewController.h"
#import "JDLTabBarController.h"
#import "AppDelegate.h"
#import "FLAddView.h"
@interface AppDelegate ()
{
    FLAddView * _addview;
}
+(NSString *)getDeviceIDInKeychain;
@end
NSString * const KEY_UDID_INSTEAD = @"com.myapp.udid.test";
@implementation AppDelegate
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}
+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}


+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}


+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}


+(NSString *)getDeviceIDInKeychain {
    NSString *getUDIDInKeychain = (NSString *)[AppDelegate load:KEY_UDID_INSTEAD];
    NSLog(@"从keychain中获取到的 UDID_INSTEAD %@",getUDIDInKeychain);
    if (!getUDIDInKeychain ||[getUDIDInKeychain isEqualToString:@""]||[getUDIDInKeychain isKindOfClass:[NSNull class]]) {
        CFUUIDRef puuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
        NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
        CFRelease(puuid);
        CFRelease(uuidString);
        NSLog(@"\n \n \n _____重新存储 UUID _____\n \n \n  %@",result);
        [AppDelegate save:KEY_UDID_INSTEAD data:result];
        getUDIDInKeychain = (NSString *)[AppDelegate load:KEY_UDID_INSTEAD];
    }
    NSLog(@"最终 ———— UDID_INSTEAD %@",getUDIDInKeychain);
    return getUDIDInKeychain;
}

-(void)verbGetDeviceIDInKeychain{
    
    NSString * string = [AppDelegate getDeviceIDInKeychain];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"] isEqualToString:string]) {
        return;
    }
    AVQuery *confirgQuery = [AVQuery queryWithClassName:@"user"];
    [confirgQuery whereKey:@"uuid" equalTo:string];
    [confirgQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (objects.count) {
            
            [[NSUserDefaults standardUserDefaults]setObject:string forKey:@"uuid"];
            return ;
            
            
            
            
            
        }else{
            
            AVObject * product = [AVObject objectWithClassName:@"user"];
            [product setObject:string forKey:@"uuid"];
            [product saveEventually:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    [[NSUserDefaults standardUserDefaults]setObject:string forKey:@"uuid"];
                    
                    NSLog(@"succeess");
                }
            }];
            
        }
        
        
        
        
    }];
    
    
}
-(void)verbGetDeviceIDFA{
    
    NSString * idfa=  [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"idfa"] isEqualToString:idfa]) {
        return;
    }
    AVQuery *confirgQuery = [AVQuery queryWithClassName:@"idfa"];
    [confirgQuery whereKey:@"uuid" equalTo:idfa];
    [confirgQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (objects.count) {
            
            [[NSUserDefaults standardUserDefaults]setObject:idfa forKey:@"uuid"];
            return ;
            
            
            
            
            
        }else{
            
            AVObject * product = [AVObject objectWithClassName:@"idfa"];
            [product setObject:idfa forKey:@"uuid"];
            [product saveEventually:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    [[NSUserDefaults standardUserDefaults]setObject:idfa forKey:@"uuid"];
                    
                    NSLog(@"succeess");
                }
            }];
            
        }
        
        
        
        
    }];
    
    
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    
    
    
}
//计算两个日期之间的天数
- (NSInteger) calcDaysFromBegin:(NSDate *)beginDate end:(NSDate *)endDate

{
    
    //创建日期格式化对象
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    
    
    
    //取两个日期对象的时间间隔：
    
    //这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:typedef double NSTimeInterval;
    
    NSTimeInterval time=[endDate timeIntervalSinceDate:beginDate];
    
    
    
    int days=((int)time)/(3600*24);
    
    //int hours=((int)time)%(3600*24)/3600;
    
    //NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];
    
    return days;
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
     [AVOSCloud setApplicationId:@"8YmhvMpCtXva1CCGgk8tzPIi-gzGzoHsz" clientKey:@"yfeQI2xD01PfWVb2lafWpeaP"];
    UMConfigInstance.appKey = @"5c3d7d4eb465f5d89600053e";
    UMConfigInstance.channelId = @"";
    
    [MobClick startWithConfigure:UMConfigInstance];
    [MobClick setLogEnabled:YES];

    
    AFNetworkReachabilityManager * manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"网络状态未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"NotReachable" object:nil];
                
                break;
            case  AFNetworkReachabilityStatusReachableViaWWAN:
                [self verbGetDeviceIDInKeychain];
                [self verbGetDeviceIDFA];
                NSLog(@"3G|4G蜂窝移动网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [self verbGetDeviceIDInKeychain];
                [self verbGetDeviceIDFA];
                NSLog(@"WIFI网络");
                break;
            default:
                break;
        }
    }];
    
    [manager startMonitoring];


    NSString * currentController = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentController"];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"1" forKey:@"Purchased"];
    if ([[user objectForKey:@"Purchased"] isEqualToString:@"1"]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy.MM.dd"];
        NSInteger day = [self calcDaysFromBegin:[formatter dateFromString:[[NSUserDefaults standardUserDefaults] objectForKey:@"strDate"]] end:[formatter dateFromString:[formatter stringFromDate:[NSDate date]]]];
        NSLog(@"daydayday = %ld", day);
        if (day < 7) {
    
            self.window =[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
            
            JDLTabBarController *tabbarVc =[[JDLTabBarController alloc] init];
            tabbarVc.addBlock = ^(UIButton * button) {
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"add"object:@(0)];
                _addview = [[FLAddView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
                _addview.cancelBlock = ^(UIButton * button) {
                    [_addview removeFromSuperview];
                };
                _addview.videoBlock = ^(UITapGestureRecognizer * tap) {
                    [_addview removeFromSuperview];
                    tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                    FLVideoDrawViewController  * vc =[[FLVideoDrawViewController alloc]init];
                    
                    [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                    //tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                };
                _addview.audioBlock = ^(UITapGestureRecognizer * tap) {
                    
                    [_addview removeFromSuperview];
                    tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                    FLRecordedViewController * vc =[[FLRecordedViewController alloc]init];
                    [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                    // tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                };
                [self.window addSubview:_addview];
                
            };
            self.window.rootViewController =tabbarVc;
            
            
            
            [self.window makeKeyAndVisible];
            
            
        }
        else {
            FLRestorePurchaseViewController * vc =[[FLRestorePurchaseViewController alloc]init];

            self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:vc];

        }

    }else{
        if ([currentController isEqualToString:@"FLRestorePurchaseViewController"]) {
            FLRestorePurchaseViewController * vc =[[FLRestorePurchaseViewController alloc]init];

            self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:vc];

        }else{
            FLPagingScrollViewController * vc =[[FLPagingScrollViewController alloc]init];

            self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:vc];

        }


    }

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
